<?php

namespace Plugins\IMApi\Middlewares;

use App\Util\ApiAuth;
use App\Util\Helper;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Sc\Util\ScTool;


class AuthMiddleware implements MiddlewareInterface
{

    /**
     * Process an incoming server request.
     *
     * Processes an incoming server request in order to produce a response.
     * If unable to produce the response itself, it may delegate to the provided
     * request handler to do so.
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $queryParams = $request->getQueryParams();
        $token = $queryParams['token'] ?? '';
        if ($token) {
            try {
                $tokenData = ScTool::jwt(Helper::getConfig('jwt.default', []))->tokenVerify($token, false);

                ApiAuth::set($tokenData);
            } catch (\Exception) {}
        }

        return $handler->handle($request);
    }
}